package com.woniuxy.realm;

import com.woniuxy.entity.Perms;
import com.woniuxy.entity.Role;
import com.woniuxy.entity.User;
import com.woniuxy.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class MyRealm  extends AuthorizingRealm {
    //注入service
    @Autowired
    private UserService userService;

    //用来从数据库获取角色信息、权限信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("正在获取角色、权限信息...");
        //通过当前用户的账号去数据库中查询出当前用户的角色信息
         String account = (String) principalCollection.getPrimaryPrincipal();
         System.out.println(account);
        //假设通过账号找到了角色信息 一个用户可以有多个角色
        Set<String> roles = new HashSet<>();
        //通过角色查询角色对应的权限信息
        Set<String> perms = new HashSet<>();

        User user = userService.findRolesAndPerms(account);
        //将user中的角色信息放到roles集合中
       for (Role role : user.getRoles()){
               //角色
            roles.add(role.getRname());
            for (Perms p : role.getPerms()){
                //权限
                perms.add(p.getPname());
            }
        }
       //授权info
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(perms);

        return info;
    }
    //获取认证信息(判断账号及账号密码的信息)
    //如果方法返回null,表示没找到对应的账号，shiro就会报账号异常
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("正在进行认证");
        //获取到账号，然后通过账号作为查询条件到数据库中查询账号信息（账号，密码等）
        String account = (String) authenticationToken.getPrincipal();//获取账号
        String pwd = new String((char[]) authenticationToken.getCredentials());
        System.out.println(account+","+pwd);

        //调用service方法查询数据库（还未做）
        //userService.findUserByAcount(account);

        User user = userService.findUserByAccount(account);

        //创建认证info对象
        SimpleAuthenticationInfo info =
                new SimpleAuthenticationInfo(user.getAccount(),user.getPwd(),getName());

        return info;
    }
}
